﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace YunShop_WebAPI.BLL
{
    /// <summary> 
    /// CommonFun
    /// </summary> 
    public static class CommonFun
    {
        public static int mRptPageSize = 100;

        public static string GetJObjectValue(Newtonsoft.Json.Linq.JObject jObject, string key)
        {
            try
            {
                var r = jObject[key];
                return r == null ? "" : r.ToString();
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string GetValidJson(string json)
        {
            if (string.IsNullOrEmpty(json)) return "[]";
            string myjson = "";
            try
            {
                if (json.Substring(0, 1) != "[")
                    myjson = "[" + json;
                else
                    myjson = json;
                if (json.Substring(json.Length - 1, 1) != "]")
                    myjson = myjson + "]";
            }
            catch
            {
            }
            return myjson;
        }

        public static string GetNumberAlpha(string source)
        {
            string pattern = "[A-Za-z0-9]";
            string strRet = "";
            MatchCollection results = Regex.Matches(source, pattern);
            foreach (var v in results)
            {
                strRet += v.ToString();
            }
            return strRet;
        }

        public static string GetSyncDataBase()
        {
            try
            {
                DateTime dt = DateTime.Now;
                int mYear = dt.Year;
                string mSyncDataBase = System.Configuration.ConfigurationManager.AppSettings["SyncDataBase"].ToString();
                if (mSyncDataBase == "") mSyncDataBase = "KingCloudShop";
                return mSyncDataBase;
            }
            catch
            {
                return "KingCloudShop";
            }
        }

        public static bool ContainChinese(string input)
        {
            string pattern = "[\u4e00-\u9fbb]";
            return Regex.IsMatch(input, pattern);
        }

        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static Int64 GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        public static string ConvertToString(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return "";
                }
                if (obj == DBNull.Value)
                {
                    return "";
                }
                return Convert.ToString(obj);
            }
            catch (Exception E)
            {
                return "";
            }
        }

        public static Boolean ConvertToBoolean(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return false;
                }
                if (obj == DBNull.Value)
                {
                    return false;
                }
                return Convert.ToBoolean(obj);
            }
            catch (Exception E)
            {
                return false;
            }
        }

        public static int ConvertBooleanToInt(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }

                if (CommonFun.ConvertToString(obj) == "true") return 1;

                return CommonFun.ConvertToString(obj) == "true" ? 1 : 0;
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        public static Boolean ConvertIntToBoolean(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return false;
                }
                if (obj == DBNull.Value)
                {
                    return false;
                }

                if (CommonFun.ConvertToInt(obj) == 1) return true;

                return false;
            }
            catch (Exception E)
            {
                return false;
            }
        }

        public static string ConvertToBooleanStr(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return "false";
                }
                if (obj == DBNull.Value)
                {
                    return "false";
                }

                if (CommonFun.ConvertToString(obj).ToLower() == "true") return "true";
                if (CommonFun.ConvertToInt(obj) == 1) return "true";

                return "false";
            }
            catch (Exception E)
            {
                return "false";
            }
        }

        public static string ConvertToDateNow(Object obj)
        {
            DateTime mDate = DateTime.Now;
            try
            {
                if (obj == null)
                {

                    return mDate.ToString("yyyy-MM-dd");
                }
                if (obj == DBNull.Value)
                {
                    return mDate.ToString("yyyy-MM-dd");
                }
                return Convert.ToDateTime(obj).ToString("yyyy-MM-dd"); ;
            }
            catch
            {
                return mDate.ToString("yyyy-MM-dd"); ;
            }
        }

        public static DateTime ConvertToDateTime(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return Convert.ToDateTime("1990-01-01 01:01:01");
                }
                if (obj == DBNull.Value)
                {
                    return Convert.ToDateTime("1990-01-01 01:01:01");
                }
                return Convert.ToDateTime(obj);
            }
            catch
            {
                return Convert.ToDateTime("1990-01-01 01:01:01");
            }
        }

        public static string ConvertToDate(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return Convert.ToDateTime("1990-01-01").ToString("yyyy-MM-dd");
                }
                if (obj == DBNull.Value)
                {
                    return Convert.ToDateTime("1990-01-01").ToString("yyyy-MM-dd");
                }
                return Convert.ToDateTime(obj).ToString("yyyy-MM-dd"); ;
            }
            catch
            {
                return Convert.ToDateTime("1990-01-01").ToString("yyyy-MM-dd");
            }
        }

        public static decimal ConvertToDecimal(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToDecimal(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        public static double ConvertToDouble(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToDouble(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        public static int ConvertToInt(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToInt32(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        public static Int64 ConvertToBigInt(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToInt64(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }


        public static string GetIdentifyCode()
        {
            char[] constant =
                              {
                                '0','1','2','3','4','5','6','7','8','9'
                              };
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
            Random rd = new Random();
            for (int i = 0; i < 4; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }

        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }

        /// <summary>
        /// DataTable转Hashtable
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static Hashtable GetHashTable(DataTable dt)
        {
            try
            {
                Hashtable hash = new Hashtable();
                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        foreach (DataColumn col in dt.Columns)
                        {
                            hash.Add(col.ColumnName, dt.Rows[i][col.ColumnName]);
                        }
                    }
                    return hash;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// DataTable转ArrayList
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ArrayList DataTableToArrayList(DataTable data)
        {
            ArrayList array = new ArrayList();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow row = data.Rows[i];
                Hashtable record = new Hashtable();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    object cellValue = row[j];
                    if (cellValue.GetType() == typeof(DBNull))
                    {
                        cellValue = null;
                    }
                    record[data.Columns[j].ColumnName] = cellValue;
                }
                array.Add(record);
            }
            return array;
        }

        //删除空行
        public static void RemoveEmpty(DataTable dt)
        {
            List<DataRow> removelist = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool IsNull = true;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                    {
                        IsNull = false;
                    }
                }
                if (IsNull)
                {
                    removelist.Add(dt.Rows[i]);
                }
            }
            for (int i = 0; i < removelist.Count; i++)
            {
                dt.Rows.Remove(removelist[i]);
            }
        }

        /// <summary>
        /// 中英文混排字符串长度
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static int Text_Length(string Text)
        {
            int len = 0;
            for (int i = 0; i < Text.Length; i++)
            {
                byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2; //如果长度大于1，是中文，占两个字节，+2
                else
                    len += 1;  //如果长度等于1，是英文，占一个字节，+1
            }
            return len;
        }

        public static string ToBase64String(string Text)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(Text);
            string base64Str = Convert.ToBase64String(b);
            return base64Str;
        }

        public static string FromBase64String(string base64Text)
        {
            byte[] c = Convert.FromBase64String(base64Text);
            string Str = System.Text.Encoding.Default.GetString(c);
            return Str;
        }

        public static bool isNumberic(string Str)
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            if (rex.IsMatch(Str))
                return true;
            else
                return false;
        }

        static string strRight(string strSrc, int iCount)
        {
            if (strSrc == null || strSrc.Length <= iCount)
                return strSrc;
            return strSrc.Substring(strSrc.Length - iCount);
        }

        public static string NumberAdd(string number)
        {
            if (string.IsNullOrEmpty(number))
                return "1001";
            if (isNumberic(number))
            {
                string str = (CommonFun.ConvertToBigInt(number) + 1).ToString();
                if (str.Length < number.Length)
                    str = strRight(("000000000000000000" + str), number.Length);
                return str;
            }

            int length = number.Length;
            int lastchar = ((int)number.ToCharArray()[length - 1]) == 57 ? 64 : ((int)number.ToCharArray()[length - 1]);
            lastchar = lastchar == 90 ? 96 : lastchar;
            lastchar = lastchar == 122 ? 48 : lastchar;
            string Number = number.Substring(0, length - 1) + (char)(lastchar + 1);
            return Number;
        }
    }

    public class Thumb
    {
        public static void ReMakeThumb(HttpContext context, string filepath, string CorpID)
        {
            if (string.IsNullOrEmpty(filepath) || filepath.IndexOf("NoImage") > -1)
                return;
            String savePath = "/Upload/";
            filepath = context.Server.MapPath(savePath) + filepath.Replace("/Upload/", "").Replace("/", "\\");
            string newThumb = filepath.Replace("\\" + CorpID + "\\", "\\" + CorpID + "\\Thumb\\");
            if (File.Exists(newThumb))
                File.Delete(newThumb);
            MakeThumbnail(filepath, newThumb, 179, 179, "HW");
        }

        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                 
                    break;
                case "W"://指定宽，高按比例                     
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板 
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw new Exception(e.Message + ",检查目录写权限");
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}
